#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：tools 
@File ：音视频合并.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/1/15 22:13 
"""

import os
import subprocess


def merge_audio_video(audio_folder, video_folder, output_folder):
	# 创建输出文件夹，如果不存在
	if not os.path.exists(output_folder):
		os.makedirs(output_folder)

	# 获取音频文件夹中的所有文件名
	audio_files = os.listdir(audio_folder)

	# 获取视频文件夹中的所有文件名
	video_files = os.listdir(video_folder)

	# 遍历音频文件
	for audio_file in audio_files:
		# 获取文件前缀
		prefix = os.path.splitext(audio_file)[0]

		# 查找具有相同前缀的视频文件
		for video_file in video_files:
			if os.path.splitext(video_file)[0] == prefix:
				# 构建完整的音频和视频文件路径
				audio_path = os.path.join(audio_folder, audio_file)
				video_path = os.path.join(video_folder, video_file)

				# 构建输出文件路径
				output_file = os.path.join(output_folder, f"{prefix}.mp4")

				# 使用ffmpeg合并音视频
				command = f"ffmpeg -i {video_path} -i {audio_path} -c:v copy -c:a aac -strict experimental {output_file}"
				subprocess.run(command, shell=True)

				print(f"Merged {audio_file} and {video_file} into {output_file}")
				break  # 假设每个音频文件只与一个视频文件匹配


# 示例用法
audio_folder = "data/audio"
video_folder = "data/video"
output_folder = "data/output"

merge_audio_video(audio_folder, video_folder, output_folder)
